import os
import sys
from flask import Flask, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_mail import Mail
from dotenv import load_dotenv

db = SQLAlchemy()
mail = Mail()

def create_app():
    # 加载 .env
    load_dotenv()

    # —— 下面是关键：根据是否在 PyInstaller 打包后的临时目录里运行，选择静态资源路径 —— 
    if hasattr(sys, '_MEIPASS'):
        # PyInstaller onefile 解压到的临时目录里
        base_dir = sys._MEIPASS
        static_folder = os.path.join(base_dir, 'frontend_dist')
    else:
        # 开发模式下，frontend_dist 在项目根目录
        this_dir = os.path.abspath(os.path.dirname(__file__))
        static_folder = os.path.normpath(os.path.join(this_dir, '..', 'frontend_dist'))

    # 创建 Flask 实例，指向前端打包后的目录
    app = Flask(
        __name__,
        static_folder=static_folder,
        static_url_path=''  # 让根路径直接映射到 static_folder
    )

    # 跨域、Mail、DB 初始化
    CORS(app, supports_credentials=True)
    from .config import Config
    app.config.from_object(Config)
    db.init_app(app)
    mail.init_app(app)

    # 注册 API 路由
    from .routes import auth_bp, bills_bp, categories_bp
    app.register_blueprint(auth_bp, url_prefix="/api")
    app.register_blueprint(bills_bp, url_prefix="/api")
    app.register_blueprint(categories_bp, url_prefix="/api")

    # 前端单页应用支持：任意不存在的路径都重定向到 index.html
    @app.route('/')
    def index():
        return send_from_directory(app.static_folder, 'index.html')

    @app.route('/<path:path>')
    def static_proxy(path):
        target = os.path.join(app.static_folder, path)
        if os.path.isfile(target):
            return send_from_directory(app.static_folder, path)
        return send_from_directory(app.static_folder, 'index.html')

    return app
